<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="农场名称" prop="name">
        <el-select
          v-model="farmTourValue"
          placeholder="请选择农场" 
          class="!w-240px" 
          style="margin-right: 10px;"
        >
          <el-option
            v-for="item in farmTourList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间" prop="timeRange">
        <el-time-picker
          v-model="value1"
          is-range
          :disabled-hours="disabledHours"
          :disabled-minutes="disabledMinutes"
          :disabled-seconds="disabledSeconds"
          range-separator="To"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="HH:mm"
        />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>

    </el-form>
    <div class="expend-echarts">
      <div style="margin:20px">
        <el-row :gutter="20">
          <el-col :span="4">总饮水(m³):{{ totalWater !== null ? totalWater : '-----' }}</el-col>
          <el-col :span="4">平均饮水(m³):{{ avgWater !== null ? avgWater : '-----'}}</el-col>
          <el-col :span="4">总耗料(kg):{{ totalWeight !== null ? totalWeight: '-----' }}</el-col>
          <el-col :span="4">平均耗料(kg):{{ avgWeight !== null ? avgWeight : '-----' }}</el-col>
        </el-row>
      </div>
      <!-- 分隔线 -->
      <el-divider />
      <div style="margin:20px"  v-loading="loading" element-loading-text="努力加载中...">
        <water :data="waterChartData"/>
      </div>
      <div style="margin:20px"  v-loading="loading" element-loading-text="努力加载中...">
        <food :data="foodChartData"/>
      </div>
    </div>
  </ContentWrap>

  
</template>

<script setup lang="ts">
import { farmExpend } from '@/api/farmTour/expend/index'
// import {defaultShortcuts ,dateFormatter } from '@/utils/formatTime';//时间函数
import water from "@/views/farmTour/component/water.vue"
import food from "@/views/farmTour/component/food.vue"
// import electricity from "@/views/farmTour/component/electricity.vue"
import { FarmTourApi, FarmTourVO } from '@/api/farmTour/index';
import { getTodayRangeString } from '@/utils/formatTime';

defineOptions({ name: 'Expend' })
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中

const farmId = ref<number>(0)
const farmTourValue = ref<any>(null) // 默认农场
const farmTourList = ref<FarmTourVO[]>([]); // 农场列表

const totalWeight = ref(0); // 总耗料
const totalWater = ref(0); // 总耗水
const avgWeight = ref(0); // 平均耗料
const avgWater = ref(0); // 平均耗水
const waterChartData  = ref([]); // 传递给水图表
const foodChartData = ref([]); // 传递给食物图表

const value1 = ref<[Date, Date] | null>(null);
// 获取当前时间
const now = new Date();
const currentHour = now.getHours();
const currentMinute = now.getMinutes();

const queryFormRef = ref() // 搜索的表单
// 获取下拉农场列表
const getList = async () => {
  loading.value = true;
  try{
    const res = await FarmTourApi.getFarmTour()
    if (res) {
      farmTourList.value = res
      // 设置默认选择为第一个农场
      if (farmTourList.value.length > 0) {
        farmTourValue.value = farmTourList.value[0].id; // 默认的农场
      }
    } 
  }catch(error){
    console.log(error,'error')
  }finally{
    loading.value = false
  }

}

// 禁用小时的函数
const disabledHours = () => {
  const hours = [];
  for (let hour = 0; hour < 24; hour++) {
    if (hour > currentHour) {
      hours.push(hour);
    }
  }
  return hours;
};

// 禁用分钟的函数
const disabledMinutes = (hour: number) => {
  const minutes = [];
  if (hour === currentHour) {
    for (let minute = 0; minute < 60; minute++) {
      if (minute > currentMinute) {
        minutes.push(minute);
      }
    }
  }
  return minutes;
};

// 禁用秒的函数
const disabledSeconds = (hour: number, minute: number) => {
  // 如果不需要禁用特定秒，可以返回空数组
  return [];
};
const queryParams = reactive({
  name: undefined,
  timeRange: []
})


const getExpendData = async () => {
  loading.value = true;
  // 获取今天的开始和结束时间
  const [todayStart, todayEnd] = getTodayRangeString();
  let startTime: string;
  let endTime: string;

  if (value1.value && value1.value.length === 2) {
    // 使用选择的时间范围
    const startHour = value1.value[0].getHours();
    const startMinute = value1.value[0].getMinutes();
    const endHour = value1.value[1].getHours();
    const endMinute = value1.value[1].getMinutes();

    // 组合时间字符串，默认秒为 00
    startTime = `${todayStart.split(' ')[0]} ${String(startHour).padStart(2, '0')}:${String(startMinute).padStart(2, '0')}:00`;
    endTime = `${todayEnd.split(' ')[0]} ${String(endHour).padStart(2, '0')}:${String(endMinute).padStart(2, '0')}:59`;
  } else {
    // 默认使用今天的时间范围，秒为 00
    startTime = `${todayStart}`; // 加上秒
    endTime = `${todayEnd}`; // 加上秒
  }

  console.log(`查询时间范围: ${startTime} To ${endTime}`);



  const params = {
    farmId: farmTourValue.value,
    createTime: [startTime, endTime]
  };
  try {
    const res = await farmExpend.getExpendApi(params);
    if (res) {
      // 提取数据
      totalWeight.value = res.totalWeight; // 总耗料
      totalWater.value = res.totalWater; // 总耗水
      avgWeight.value = res.avgWeight; // 平均耗料
      avgWater.value = res.avgWater; // 平均耗水

      // 处理图表数据
      const consumptionData = res.data;
      console.log(consumptionData,'consumptionData');
      

      // 准备图表数据
      const waterChartDataTemp = [];
      const foodChartDataTemp = [];

      for (const key in consumptionData) {
        consumptionData[key].forEach(item => {
          waterChartDataTemp.push({
            farmHouseName: item.farmHouseName,
            waterConsumption: item.waterConsumption
          });
          foodChartDataTemp.push({
            farmHouseName: item.farmHouseName,
            todayUse: item.todayUse
          });
        });
      }

      // 提交数据给图表组件
      waterChartData.value = waterChartDataTemp; // 传递给水组件
      foodChartData.value = foodChartDataTemp; // 传递给食物组件
      console.log(foodChartData.value,'foodChartData');
    } else {
      // 处理错误信息
      console.error('API错误:', res.msg);
    }
  } catch (error) {
    console.error('获取数据时出错:', error);
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery =async () => {
  await getExpendData()
}
/** 重置按钮操作 */
const resetQuery = () => {
  value1.value = null;
  queryFormRef.value.resetFields()
  handleQuery()
}



const fetchData = async () => {
  loading.value = true;
  try {
    farmId.value = farmTourValue.value; // 更新 farmId
    getExpendData()
  } catch (error) {
    console.error('获取数据时出错:', error);
  }finally{
    loading.value = false
  }
};

// 监听 farmTourValue 的变化
watch(farmTourValue, () => {
  loading.value = true;
  fetchData(); // 调用异步处理函数
  loading.value = false
});


/** 初始化 **/
onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.el-button-group{
  .el-button--primary:last-child{
    border-left-color: #ccc;
  }
  .is-active {
      background-color: #409EFF;
  }
}

.expend-box{
  margin: 20px 10px;
  padding: 10px;
  background-color: rgba(239, 246, 255, 0.996078431372549);
}

</style>